package com.auto.base.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auto.base.mapper.CompanyMapper;
import com.auto.base.pojo.Company;
import com.auto.base.pojo.CompanyExample;
import com.auto.base.pojo.CompanyExample.Criteria;
import com.auto.base.service.CompanyService;
import com.auto.common.SessionInfo;
import com.auto.util.MyJsonConfig;
import com.base.callback.MapperCallBack;
import com.base.common.CommonConstants;
import com.base.model.interfaze.FieldAppendAbstract;
import com.base.model.interfaze.FieldAppendArray;
import com.base.model.interfaze.MapperCallBackAdapter;
import com.base.util.JUtil;
import com.base.util.MapperUtil;
import com.base.util.Page;


@Transactional
@Service
@Scope("prototype")
public class CompanyServiceImpl implements CompanyService {
    @Resource 
	public SqlSessionTemplate sqlSession; 
    @Resource
    private CompanyMapper mapper;
    private SqlSession session;

    /**
     * 单个数据查询
     * 
     * @param record
     * @param callback
     * @return
     */
    @Override
    public Company findCompany(Company record, MapperCallBack callback) throws Exception {
        List<Company> records = listCompany(record, null, new Page(0, 1), callback);
        if (null != records && records.size() > 0) {
            return records.get(0);
        }
        return null;
    }

    /**
     * 单个数据查询,字段并关联外键值
     * 
     * @param record
     * @param callback
     * @return
     */
    @Override
    public JSONObject findCompanyAndFkText(Company record, MapperCallBack callback, FieldAppendArray appendArray) throws Exception {
        Company rec = findCompany(record, callback);
        JSONObject jsonobj = null;
        if (null != rec) {
            //
            jsonobj = JSONObject.fromObject(rec,MyJsonConfig.JSON_CFG);
            // 遍历
            for (FieldAppendAbstract fieldAppend : appendArray) {
                // 属性名称
                String fieldName = fieldAppend.getFieldName();
                // 列表值
                Object listVal = fieldAppend.listValues(MapperUtil.getFiledVals(rec, fieldName));
                // 外键值
                Object oldVal = jsonobj.get(fieldName);
                // 最终返回值
                Object finalVal = fieldAppend.getValue(listVal, oldVal);
                //
                jsonobj.put(fieldAppend.getFieldName() + fieldAppend.getFieldSuffix(), finalVal);
            }
        }
        return null==jsonobj?new JSONObject():jsonobj;
    }

    /**
     * 根据模型查找信息
     * 
     * @param 模型
     * @page 页面(不分页,则传null)
     * @orderByClause 排序(不需,则传null)
     * @return 对象
     * @throws Exception
     */
    @Override
    public List<Company> listCompany(Company record, String orderByClause, Page page, MapperCallBack callback) throws Exception {
        if(null == callback) callback = new MapperCallBackAdapter();
        //
        callback.doRecord(record);
        //
        CompanyExample example = new CompanyExample();
        // 去掉重复结果集
        example.setDistinct(true);
        // 分页
        if (null != page) {
            example.setPage(page);
        }
        // 排序
        if (!JUtil.isNull(orderByClause)) {
            example.setOrderByClause(orderByClause);
        }
        // 设置查询条件
        Criteria criteria = example.createCriteria();
        //
        callback.doExample(example);
        // 构建查询条件
        MapperUtil.builderCriteria(criteria, record);
        //
        callback.doCriteria(criteria);
        if (null != page) {
            // 总条数
            int count = mapper.countByExample(example);
            page.setCount(count);
        }
        // 返回查询记录
        return mapper.selectByExample(example);
    }

    /**
     * 查询,字段并关联外键值
     * 
     * @param record
     * @param orderByClause
     * @param page
     * @param callback
     * @param appendArray
     * @return
     * @throws Exception
     */
    @Override
    public JSONArray listCompanyAndFkText(Company record, String orderByClause, Page page, MapperCallBack callback, FieldAppendArray appendArray) throws Exception {
        // 属性,对应表,对应表字段
        List<Company> records = listCompany(record, orderByClause, page, callback);
        //
        JSONArray array = JSONArray.fromObject(records,MyJsonConfig.JSON_CFG);
        //
        int size = array.size();
        //
        for (FieldAppendAbstract fieldAppend : appendArray) {
            List<String> oldFieldVals = MapperUtil.getFiledVals(records, fieldAppend.getFieldName());
            Object listVal = fieldAppend.listValues(oldFieldVals);
            for (int i = 0; i < size; i++) {
                //
                JSONObject jsonobj = array.getJSONObject(i);
                //
                Object oldVal = jsonobj.get(fieldAppend.getFieldName());
                //
                Object finalVal = fieldAppend.getValue(listVal, oldVal);
                //
                jsonobj.put(fieldAppend.getFieldName() + fieldAppend.getFieldSuffix(), finalVal);
            }
        }
        return array;
    }
    
	
    /**
     * 新增数据
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public void insertCompany(Company record) throws Exception {
        // 执行操作
        int res = mapper.insertSelective(record);
        // 抛出异常
        if (res <= 0)
            throw new RuntimeException("Company表新增数据失败");
    }

    /**
     * 物理删除数据
     * 杨浩
     * @param  pks
     * @throws Exception
     */
    @Override
    public void dropCompany(String pks) throws Exception {
        if (JUtil.isNull(pks)) {
            throw new RuntimeException("删除主键不能为空");
        }
        CompanyExample example = new CompanyExample();
        // 设置查询条件
        Criteria criteria = example.createCriteria();
        criteria.andIdIn(JUtil.splitToListInteger(pks));
        // 执行操作
        int res = mapper.deleteByExample(example);
        // 抛出异常
        if (res <= 0){
        throw new RuntimeException("Company表删除数据失败");
        }
    }
    
    /**
     * 更新数据
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public void modifyCompany(Company record, MapperCallBack callback) throws Exception {
    
        callback.doRecord(record);
        //
        CompanyExample example = new CompanyExample();
        // 设置查询条件
        Criteria criteria = example.createCriteria();
        //
        callback.doExample(example);
        //
        callback.doCriteria(criteria);
        //
        if (!criteria.isValid()) {
            throw new RuntimeException("更新必须要设置条件!");
        }
        // 执行操作
        int res = mapper.updateByExampleSelective(record, example);
        // 抛出异常
        if (res <= 0) {
            throw new RuntimeException("Company表更新数据失败");
        }

    }
    
    /**
     * 更新数据
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public void modifyCompanyByPkSelective(Company record) throws Exception {
        // 执行操作
        int res = mapper.updateByPrimaryKeySelective(record);
        // 抛出异常
        if (res <= 0) {
            throw new RuntimeException("Company表更新数据失败");
        }
    }
    
    /**
     * 更新数据
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public void modifyCompanyByPk(Company record) throws Exception {
        // 执行操作
        int res = mapper.updateByPrimaryKey(record);
        // 抛出异常
        if (res <= 0) {
            throw new RuntimeException("Company表更新数据失败");
        }
    }
    
    /**
     * 总条数
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public int countCompany(Company record, MapperCallBack callback) throws Exception {
       if(null == callback) 
        {
        callback = new MapperCallBackAdapter();
        }
        //
        callback.doRecord(record);
        //
        CompanyExample example = new CompanyExample();
        // 设置查询条件
        Criteria criteria = example.createCriteria();
        //
        callback.doExample(example);
        //
        callback.doCriteria(criteria);
        // 执行操作
        int res = mapper.countByExample(example);
        return res;
    }
    
    /**
     * 总条数新增方法
     * 
     * @param record
     * @throws Exception
     */
    @Override
    public int countCompany(Company record) throws Exception {
    
        MapperCallBack callback = new MapperCallBackAdapter();
        
        callback.doRecord(record);
        //
        CompanyExample example = new CompanyExample();
        // 设置查询条件
        Criteria criteria = example.createCriteria();
         // 根据record重新构建查询条件
        MapperUtil.builderCriteria(criteria, record);
        // 执行操作
        int res = mapper.countByExample(example);
        return res;
    }
    
    /**
     * 逻辑删除数据最新方法
     * 杨浩
     * @param pks
     * @throws Exception
     */
    @Override
    public void deleteCompany(String pks) throws Exception {
        if (JUtil.isNull(pks)) {
            throw new RuntimeException("逻辑删除主键不能为空");
        }
        CompanyExample example = new CompanyExample();
        // 设置查询条件
        Criteria criteria = example.createCriteria();
        criteria.andIdIn(JUtil.splitToListInteger(pks));
        Company record = new Company();
        record.setEnabled(1);
        // 执行操作
        int res = mapper.updateByExampleSelective(record,example);
        // 抛出异常
        if (res <= 0){
        throw new RuntimeException("Company表逻辑删除数据失败");
        }
    }
    
     /**
    * 对导入进来的数据进行入库处理 
    * @param list
    * @throws Exception
    */
    @Override
	public void inputExcelData(Map<String,Object> result) throws Exception {
		List<Company> list  = (List<Company>)result.get(CommonConstants.INPUT_RESULTKEY);
		if(!list.isEmpty()){
			for(Company record: list){
				this.insertCompany(record);
			}
		}
	}
	
	 /**
     * 批量导入处理
     * @param list
     * @param request
     * @throws Exception
     */
    public void insertBeatch(List<Company> list,SessionInfo sessionInfo)
			throws Exception {
	   if(null == list || list.isEmpty()){
		   throw new RuntimeException("导入数据为空!");
	   }
		try{
			session = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			CompanyMapper m = session.getMapper(CompanyMapper.class);
			try{
				int length = list.size(),maxSize = length;
				int currentValue  = 10;
				Date date = new Date();
				//Integer addUserId = sessionInfo.getSysUser().getId();
				//String addUserName = sessionInfo.getSysUser().getUserName();
				while(length > 0){
					Company record  = list.get(length-1);
					record.setAddTime(date.getTime());
					//record.setAddUser(addUserId);
					record.setUpdateTime(record.getAddTime());
					//record.setLastUpdateUser(addUserId);
					m.insertSelective(record);
					length -- ;
				}
				session.commit();
				session.clearCache();	
			}catch(Exception e){
				session.rollback();//回滚
				throw e;
			}finally{
				session.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			//可以加入日志记录
			throw e;	
		}
	}
    
    /**
     * 批量修改
     * @param list
     * @param request
     * @throws Exception
     */
    public void modifyBeatch(List<Company> list,SessionInfo sessionInfo)
			throws Exception {
	   if(null == list || list.isEmpty()){
		   throw new RuntimeException("导入数据为空!");
	   }
		try{
			session = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			CompanyMapper m = session.getMapper(CompanyMapper.class);
			try{
				int length = list.size(),maxSize = length;
				int currentValue  = 10;
				Date date = new Date();
				//Integer addUserId = sessionInfo.getSysUser().getId();
				//String addUserName = sessionInfo.getSysUser().getUserName();
				while(length > 0){
					Company record  = list.get(length-1);
					record.setUpdateTime(date.getTime());
					//record.setAddUser(addUserId);
					//record.setLastUpdateUser(addUserId);
					m.updateByPrimaryKeySelective(record);
					length -- ;
				}
				session.commit();
				session.clearCache();	
			}catch(Exception e){
				session.rollback();//回滚
				throw e;
			}finally{
				session.close();
			}
		}catch(Exception e){
			e.printStackTrace();
			//可以加入日志记录
			throw e;	
		}
	}
}
